<template>
  <div class="inside-comment">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="layout">
          <div class="search-cmp-container">
            <el-input v-model="queryData.name"  placeholder="请输入想要查找的关键词" clearable @keyup.enter="handleSearch "/>
            <el-button type="primary" round size="large" @click="handleSearch ">搜索</el-button>
          </div>
          <div class="advanced-filters">
              <div v-for="group in filterGroups" :key="group.id" class="filter-group">
                <h3>{{ group.title }}</h3>
                <div class="filter-options">
                  <div 
                    v-for="option in group.options" 
                    :key="option.value"
                    class="filter-option"
                    :class="{ active: isOptionSelected(group.id, option.value) }"
                    @click="handleOptionSelect(group.id, option.value)"
                  >
                    {{ option.label }}
                  </div>
                </div>
              </div>
              <div class="filter-bottom">
                  <div class="left-box">
                      <span style="flex-shrink:0;">已选条件：</span>
                      <ul class="filter-tags">
                        <li 
                          v-for="groupId in activeFilterGroups" 
                          :key="groupId"
                          class="filter-tag"
                        >
                          {{ getGroupTitle(groupId) }}: 
                          <span v-if="isGroupMultiple(groupId)">
                              {{ selectedValues[groupId]
                                .filter(value => value !== '')
                                .map(value => getOptionLabel(groupId, value))
                                .join('、') }}
                          </span>
                          <span v-else>
                            {{ getOptionLabel(groupId, selectedValues[groupId]) }}
                          </span>
                          <el-icon @click="clearGroupFilters(groupId)">
                            <CloseBold />
                          </el-icon>
                        </li>
                      </ul>
                  </div>
                  <el-button type="primary" plain @click="resetAllFilters">重置筛选</el-button>
              </div>
          </div>
      </div>
    </div>
    <div class="results-section">
      <div class="layout">
        <div class="results-header">
          <div class="results-count">
            找到<span>{{queryData.total}}</span>个职位
          </div>
        </div>
        <ul class="job-list" v-loading="loading">
          <li v-for="job in tableData" :key="job.id">
            <div class="top">
              <p class="tit">{{ job.name }}</p>
              <span class="period">报名时间：{{ dayjs(job.startTime).format('YYYY-MM-DD') }} - {{ dayjs(job.deadline).format('YYYY-MM-DD') }}</span>
            </div>
            <div class="requirements">
                <div class="requirement-item">
                    <el-icon><School /></el-icon>
                    {{ getDegreeLabel(job.degree) || '学历不限' }}
                </div>
                <el-divider direction="vertical" />
                <div class="requirement-item">
                    <el-icon><Timer /></el-icon>
                    {{ getExperienceLabel(job.workExperience) || '经验不限' }}
                </div>
                <el-divider direction="vertical" />
                <div class="requirement-item">
                    <el-icon><Collection /></el-icon>
                    {{ job.major || '专业不限' }}
                </div>
                <el-divider direction="vertical" />
                <div class="requirement-item">
                    <el-icon><Location /></el-icon>
                    {{ job.address || '地点未设置' }}
                </div>
                <el-divider direction="vertical" />
                <div class="requirement-item">
                    <el-icon><User /></el-icon>
                    {{ job.age || '年龄不限' }}
                </div>
            </div>
            <div class="bottom">
              <div class="job-tags">
                <el-tag type="info" v-for="tag in job.customizationList" :key="tag">{{ tag }}</el-tag>
              </div>
              <div class="btns">
                <el-button type="primary" @click="handleJobClick(job.id)">查看详情</el-button>
                <el-button :type="job.isCollect?'primary':''" plain :icon="job.isCollect ? StarFilled : Star" @click="toggleFavorite(job)">{{ job.isCollect ? '已收藏' : '收藏' }}</el-button>
                <el-popover placement="right" :width="200" trigger="click" @show="generateQRCode(job.id)" @click.stop>
                    <template #reference>
                      <el-button plain :icon="Share" @click.stop>分享</el-button>
                    </template>
                    <div class="share-content">
                      <img v-if="qrcodeUrls[job.id]" :src="qrcodeUrls[job.id]" class="qrcode-img" alt="分享二维码" />
                      <div class="share-link">
                        <el-input v-model="shareLinks[job.id]" size="small" readonly>
                          <template #append>
                            <el-button @click="copyLink(job.id)">复制</el-button>
                          </template>
                        </el-input>
                      </div>
                      <div class="share-tip">扫描二维码分享</div>
                    </div>
                  </el-popover>
              </div>
            </div>
          </li>
        </ul>
        <PaginationView
        :total="queryData.total"
        :pageSize="queryData.pageSize"
        :currentPage="queryData.currentPage"
        :allChoose="isAllChooseBtn"
        :pageChoose="isPageChooseBtn"
        :options="batchOptions"
        :checkedNum="checkedNum"
        :canChoose="false"
        @changeSize="handleSizeChange"
        @currentChange="handleCurrentChange"
        @changePageChoose="handlePageChoose"
        @changeAllChoose="handleAllChoose"
        @invertChoose="handleInvertChoose"
        @checkOption="handleBatchOptions"
        @refreshList="getJobs"
        @cancelChoose="handleResetPagination"
      />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted,reactive,computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Share,School, Collection, Timer, User, Location,Star, StarFilled, CloseBold } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { selectSeekerPage,insertPostCollect, deletePostCollect } from '@/api/position'
import { tableList as mixTable } from '@ruifox-cms/utils'
import QRCode from 'qrcode'
import dayjs from 'dayjs'
import { useStore } from "vuex";

const store = useStore();
const route = useRoute()
const router = useRouter()
//搜索
// const keyWord = ref('')
//分页器
const {
  queryData,
  tableData,
  // tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  // checkedList,
  // isAllSearch,
  // getTableData,
  //   handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  // handleCheckTable,
  handleResetPagination,
} = mixTable({
  getListApi: selectSeekerPage,
});
const defaultForm = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  groupId: store.state.base.userInfo.groupId,
  name: ""
})
Object.assign(queryData, defaultForm);

// 处理搜索
const handleSearch = () => {
  // 更新路由参数
  router.push({
    path: '/recruitment/user/jobs',
    query: { 
      keyword: queryData.name.trim() || undefined, // 如果为空则不传递参数
    }
  })
}
// 监听路由参数变化
watch(() => route.query.keyword, (newKeyword) => {
  if (newKeyword) {
    queryData.name = newKeyword
  }
  getJobs()
})
const loading = ref(false);
//获取职位
const getJobs = async () => {
  loading.value = true;
  try {
    const res = await selectSeekerPage(queryData);
    if (res.code === 20000) {
      queryData.total = res.data.total;
      tableData.value = res.data.list;
    }
  } catch (error) {
    console.error('获取职位数据失败:', error);
  } finally {
    loading.value = false;
  }
}


// 筛选配置
const filterGroups = ref([
  {
    id: 'degree',
    title: '学历要求',
    multiple: false, // 单选模式
    options: [
      { value: '', label: '不限' },
      { value: '1', label: '初中及以下' },
      { value: '2', label: '中专/中技' },
      { value: '3', label: '高中' },
      { value: '4', label: '大专' },
      { value: '5', label: '本科' },
      { value: '6', label: '硕士' },
      { value: '7', label: '博士' }
    ]
  },
  {
    id: 'workExperience',
    title: '工作经验',
    multiple: true, // 单选模式
    options: [
      { value: '', label: '不限' },
      { value: '1', label: '应届生' },
      { value: '2', label: '1-3年' },
      { value: '3', label: '3-5年' },
      { value: '4', label: '5年以上' }
    ]
  }
]);

// 获取学历标签
const getDegreeLabel = (degreeValue) => {
  const degreeGroup = filterGroups.value.find(g => g.id === 'degree');
  if (!degreeGroup) return degreeValue;
  
  const option = degreeGroup.options.find(o => o.value === degreeValue);
  return option ? option.label : degreeValue;
};

// 获取经验标签
const getExperienceLabel = (experienceValue) => {
  const expGroup = filterGroups.value.find(g => g.id === 'workExperience');
  if (!expGroup) return experienceValue;
  
  const option = expGroup.options.find(o => o.value === experienceValue);
  return option ? option.label : experienceValue;
};

// 选中的值
const selectedValues = ref({});

// 检查选项是否被选中
const isOptionSelected = (groupId, optionValue) => {
  const values = selectedValues.value[groupId];
  if (values === undefined) return false;
  if (Array.isArray(values)) {
    // 多选模式
    return values.includes(optionValue);
  } else {
    // 单选模式
    return values === optionValue;
  }
};
// 处理选项选择
const handleOptionSelect = (groupId, optionValue) => {
  const group = filterGroups.value.find(g => g.id === groupId);
  
  if (!group) return;
  
  if (group.multiple) {
    // 多选模式
    const currentValues = [...selectedValues.value[groupId]];
    const index = currentValues.indexOf(optionValue);
    
    // 如果选中"不限"，则清空其他选项
    if (optionValue === '') {
      selectedValues.value[groupId] = [''];
    } else {
      // 移除"不限"选项
      const unlimitedIndex = currentValues.indexOf('');
      if (unlimitedIndex > -1) {
        currentValues.splice(unlimitedIndex, 1);
      }
      
      // 添加或移除当前选项
      if (index > -1) {
        currentValues.splice(index, 1);
      } else {
        currentValues.push(optionValue);
      }
      
      // 如果没有选择任何选项，自动选中"不限"
      if (currentValues.length === 0) {
        currentValues.push('');
      }
      
      selectedValues.value[groupId] = currentValues;
    }
  } else {
    // 单选模式
    selectedValues.value[groupId] = optionValue;
  }

  // 获取职位列表
  updateFormData()
  getJobs()
};


// 清除单个筛选组的选择
const clearGroupFilters = (groupId) => {
  const group = filterGroups.value.find(g => g.id === groupId);
  if (!group) return;
  selectedValues.value[groupId] = group.multiple ? [''] : '';

  updateFormData()
  getJobs()
};

// 重置所有筛选条件
const resetAllFilters = () => {
  Object.assign(queryData, defaultForm);
  filterGroups.value.forEach(group => {
    selectedValues.value[group.id] = group.multiple ? [''] : '';
  });
  updateFormData()
  getJobs()
};
// 获取组标题
const getGroupTitle = (groupId) => {
  const group = filterGroups.value.find(g => g.id === groupId);
  return group ? group.title : '';
};

// 获取选项标签
const getOptionLabel = (groupId, optionValue) => {
  const group = filterGroups.value.find(g => g.id === groupId);
  if (!group) return '';
  
  const option = group.options.find(o => o.value === optionValue);
  return option ? option.label : '';
};

// 检查组是否为多选模式
const isGroupMultiple = (groupId) => {
  const group = filterGroups.value.find(g => g.id === groupId);
  return group ? group.multiple : false;
};

// 是否有选中的筛选条件
// const hasSelectedFilters = computed(() => {
//   return Object.values(selectedValues.value).some(value => {
//     if (Array.isArray(value)) {
//       return value.length > 0 && !(value.length === 1 && value[0] === '');
//     }
//     return value !== '';
//   });
// });

// 检查组是否有活跃的筛选条件（除了"不限"）
const hasActiveFilterInGroup = (groupId) => {
  const selected = selectedValues.value[groupId];
  
  if (!selected) return false;
  
  if (Array.isArray(selected)) {
    return selected.some(value => value !== '');
  }
  
  return selected !== '';
};

// 计算有活跃筛选条件的组ID数组
const activeFilterGroups = computed(() => {
  return Object.keys(selectedValues.value).filter(groupId => {
    return hasActiveFilterInGroup(groupId);
  });
});
// 更新表单数据 - 动态映射selectedValues的键名到queryData
const updateFormData = () => {
  // 清空原有的筛选参数（保留分页和固定参数）
  Object.keys(queryData).forEach(key => {
    if (!['total', 'currentPage', 'pageSize', 'groupId', 'name'].includes(key)) {
      delete queryData[key];
    }
  });
  
  // 动态添加筛选参数
  Object.entries(selectedValues.value).forEach(([groupId, value]) => {
    if (Array.isArray(value)) {
      // 多选模式：将数组转换为逗号分隔的字符串
      const filteredValues = value.filter(v => v !== '');
      if (filteredValues.length > 0) {
        queryData[groupId] = filteredValues.join(',');
      } else {
        // 如果没有选中值，不添加该参数或设为空
        queryData[groupId] = '';
      }
    } else {
      // 单选模式
      if (value !== '') {
        queryData[groupId] = value;
      } else {
        // 如果是"不限"，不添加该参数或设为空
        queryData[groupId] = '';
      }
    }
  });
};

//收藏职位
const toggleFavorite = async (job) => {
  try {
    // 立即更新UI状态
    job.isCollect = !job.isCollect;
    
    if (job.isCollect) {
      // 调用收藏接口
      await insertPostCollect({ postId: job.id });
    } else {
      // 调用取消收藏接口
      await deletePostCollect({ postId: job.id });
    }
  } catch (error) {
    // 失败时回滚UI状态
    job.isCollect = !job.isCollect;
    console.error('收藏操作失败:', error);
  }
};
onMounted(() => {
  filterGroups.value.forEach(group => {
    selectedValues.value[group.id] = group.multiple ? [''] : '';
  });
  // if (router.currentRoute.value.query.groupId) {
  //   localStorage.setItem('recruitment-groupId', router.currentRoute.value.query.groupId)
  // }
  if (route.query.keyword) {
    queryData.name = route.query.keyword
  }
  updateFormData()
  getJobs()
})

// 方法
const handleJobClick = jobId => {
  router.push(`/recruitment/user/apply?jobId=${jobId}`)
}

const qrcodeUrls = ref({})
const shareLinks = ref({})

const generateQRCode = async jobId => {
  const link = `${window.location.origin}${process.env.BASE_URL}recruitment/user/apply?jobId=${jobId}&groupId=${localStorage.getItem('recruitment-groupId')}`
  shareLinks.value[jobId] = link

  if (!qrcodeUrls.value[jobId]) {
    try {
      const url = await QRCode.toDataURL(link, {
        width: 120, // 减小二维码尺寸
        margin: 0,
        color: {
          dark: '#000',
          light: '#fff'
        }
      })
      qrcodeUrls.value[jobId] = url
    } catch (err) {
      console.error(err)
    }
  }
}

const copyLink = async jobId => {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(shareLinks.value[jobId])
    } else {
      const textArea = document.createElement('textarea')
      textArea.value = shareLinks.value[jobId]
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      document.execCommand('copy')
      textArea.remove()
    }
    ElMessage.success('链接已复制')
  } catch (err) {
    console.error(err)
    ElMessage.error('复制失败')
  }
}

</script>

<style lang="scss" scoped>
  .inside-comment {
    .filter-section {
      background: #f8f9fa;
      box-sizing: border-box;
      margin-top: px2rem(-54);
      padding-top: px2rem(94);
      padding-bottom: px2rem(40);
      .search-cmp-container {
          border:1px solid var(--el-color-primary);
          border-radius:100px;
          display: flex;
          padding:px2rem(5) px2rem(5) px2rem(5) px2rem(12);
          box-sizing: border-box;
          :deep(.el-input__wrapper) {
              box-shadow: unset;
              background-color: transparent;
          }
          input {
              border-radius: 100px;
          }
          .el-button {
              font-size: px2rem(18);
          }
      }
      .advanced-filters {
        margin-top: px2rem(20);
        padding: px2rem(20);
        box-sizing: border-box;
        background-color: white;
        border-radius: 10px;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        .filter-group {
          margin-bottom: px2rem(15);
          h3 {
            font-size: px2rem(16);
            margin-bottom: px2rem(10);
          }
          .filter-options {
            display: flex;
            flex-wrap: wrap;
            gap: px2rem(10);
          }
          .filter-option {
            padding: px2rem(5) px2rem(15);
            box-sizing: border-box;
            border: 1px solid #ddd;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: px2rem(16);
            &.active {
              background-color: var(--el-color-primary);
              color: white;
              border-color: var(--el-color-primary);
            }
          }
        }
        .filter-bottom {
          margin-top: px2rem(20);
          padding-top: px2rem(10);
          box-sizing: border-box;
          border-top: 1px solid #e4e4e4;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .left-box {
            display: flex;
            align-items: center;
            font-size: px2rem(16);
            line-height: 1;
            .filter-tags {
              padding: 0;
              display: flex;
              flex-wrap: wrap;
              align-items: center;
              gap: px2rem(10);
              .filter-tag {
                display: flex;
                align-items: center;
                border: 1px solid var(--el-color-primary);
                border-radius: 100px;
                color: var(--el-color-primary);
                flex-shrink: 0;
                padding: px2rem(5) px2rem(12);
                box-sizing: border-box;
                i {
                  margin-left: px2rem(5);
                  cursor: pointer;
                }
              }
            }
          }
        }
      }
    }
    .results-section {
      padding: px2rem(40) 0;
      box-sizing: border-box;
      .layout {
        .results-header {
          margin-bottom: px2rem(40);
          .results-count {
            font-size: px2rem(18);
            color: #666;
            span {
              color: var(--el-color-primary);
              font-weight: bold;
            }
          }
        }
        .job-list {
          padding: 0;
          li {
            display: flex;
            flex-direction: column;
            border: 1px solid #eee;
            border-radius: 8px;
            padding: px2rem(20);
            box-sizing: border-box;
            margin-bottom: px2rem(20);
            transition: all 0.3s;
            &:hover {
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
              transform: translateY(-2px);
            }
            .top {
                display: flex;
                align-items: center;
                justify-content: space-between;
                .tit {
                    font-size: px2rem(18);
                    color: var(--el-color-primary);
                }
                .period {
                    font-size: px2rem(16);
                    flex-shrink: 0;
                    color: #666;
                    line-height: 1;
                }
            }
            .requirements {
                margin-top: px2rem(20);
                display: flex;
                align-items: center;
                font-size: px2rem(14);
                line-height: 1;
                color: #666;
                flex-wrap:wrap;
                gap: px2rem(5);
                .requirement-item {
                    display: flex;
                    align-items: center;
                    
                }
            }
            .bottom {
              margin-top: px2rem(20);
              display: flex;
              justify-content: space-between;
              align-items: center;
              .job-tags {
                display: flex;
                flex-wrap:wrap;
                gap:px2rem(10);
              }
            }
          }
        }
      }
    }
  }

.share-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 8px;
  box-sizing: border-box;
  .qrcode-img {
    width: 120px; // 减小二维码尺寸
    height: 120px;
    display: block;
  }

  .share-link {
    width: 100%;
  }

  .share-tip {
    color: #909399;
    font-size: 12px;
  }
}
@media (max-width:960px) {
  .inside-comment {
    .filter-section {
      padding-top: 70px;
      .advanced-filters .filter-bottom .left-box {
        flex-wrap: wrap;
        gap: 10px;
      }
    }
    .results-section .layout {
      .results-header {
        margin-bottom: 20px;
      }
      .job-list li {
        .top {
          flex-wrap: wrap;
          gap:10px;
        }
        .bottom {
          flex-wrap: wrap;
          gap: 10px;
        }
      }
    }
  }
}
</style>
